//
//  ScenicoNavMapCtrl.m
//  Traveling
//
//  Created by 尹桥印 on 15/6/20.
//  Copyright (c) 2015年 长沙市岳麓区立早网络科技有限公司. All rights reserved.
//

#import "ScenicoNavMapCtrl.h"
#import "CFAnotationView.h"
#import "CFAnnotation.h"
#import <BaiduMapAPI/BMapKit.h>
#import "HomeDataTool.h"
#import "LocationInfo.h"

@interface ScenicoNavMapCtrl ()<BMKMapViewDelegate,BMKLocationServiceDelegate>
@property (nonatomic,strong)BMKMapView *mapView;
@property (nonatomic,strong)NSMutableArray *annotationArray;
@property (nonatomic, strong) BMKLocationService *locService;
@property (nonatomic, strong) ScenicoItemInfo *itemInfo;
@property (nonatomic, strong) BMKUserLocation *userLocation;
@property (nonatomic, weak) UIButton *userLocationBtn;
@end

@implementation ScenicoNavMapCtrl

-(NSMutableArray *)annotationArray{
    if (!_annotationArray) {
        _annotationArray = [NSMutableArray array];
    }
    return _annotationArray;
}

- (instancetype)initWithScenicoItemInfo:(ScenicoItemInfo *)itemInfo
{
    self = [super init];
    if (self) {
        self.itemInfo = itemInfo;
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [BMKLocationService setLocationDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
    [BMKLocationService setLocationDistanceFilter:100.f];
    _locService = [[BMKLocationService alloc]init];
    _locService.delegate = self;
    //启动LocationService
    [_locService startUserLocationService];
    
    //地图初始化
    BMKMapView *mapView = [[BMKMapView alloc]initWithFrame:self.view.frame];
    [mapView setDelegate:self];
    mapView.showsUserLocation = YES;//显示定位图层
//    mapView.userTrackingMode = BMKUserTrackingModeFollow;
    [self.view addSubview:mapView];
    self.mapView = mapView;
    
    [mapView addObserver:self forKeyPath:@"userTrackingMode" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
    
    //添加我的位置的按钮
    UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(0, self.view.height-150-64, 50, 50)];
    [button setImage:[UIImage imageNamed:@"huise"] forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:@"lanse"] forState:UIControlStateSelected];
    [button addTarget:self action:@selector(toSelfLocation:) forControlEvents:UIControlEventTouchUpInside];
//    button.selected = YES;
    self.userLocationBtn = button;
    
    [self.view addSubview:button];
    
    [HomeDataTool getLocationListWithContentId:self.itemInfo.id success:^(LocationListRes *result) {
        if (result.isSucc) {
            for (LocationInfo *info in result.datas) {
                CFAnnotation *annotation = [[CFAnnotation alloc] init];
                annotation.icon = @"icon_p";
                annotation.coordinate = CLLocationCoordinate2DMake(info.latitude,info.longitude);
                annotation.locationInfo = info;
                annotation.title = info.title;
                [self.annotationArray addObject:annotation];
                [self.mapView addAnnotation:annotation];
            }
            CFAnnotation *annotation = [self.annotationArray lastObject];
            [self setMapViewRegion:annotation.coordinate Coordinate:1];
        }else{
            [DialogUtils showTips:result.msg];
        }
    } failure:^(NSError *error) {
        [DialogUtils showTips:@"景点导航坐标加载失败"];
    }];
    
}

- (void)toSelfLocation:(UIButton *)sender {
    if (sender.selected) {
        self.userLocationBtn.selected = NO;
        self.mapView.userTrackingMode = BMKUserTrackingModeNone;
    }else{
        self.mapView.userTrackingMode = BMKUserTrackingModeFollow;
        if (self.userLocation.location!=nil) {
            [self setMapViewRegion:self.userLocation.location.coordinate Coordinate:0.1];
        }
    }
}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [_mapView viewWillAppear];
    _mapView.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [_mapView viewWillDisappear];
    _mapView.delegate = nil; // 不用时，置nil
}

/**
 *  设置地图显示的中心位置 以及跨度
 *
 *  @param center 中心位置
 */
-(void)setMapViewRegion:(CLLocationCoordinate2D)center Coordinate:(double)coordinate{
    BMKCoordinateSpan span = BMKCoordinateSpanMake(coordinate, coordinate);
    BMKCoordinateRegion regin = BMKCoordinateRegionMake(center, span);
    [self.mapView setRegion:regin animated:YES];
}


#pragma mark - 百度地图代理
-(BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id<BMKAnnotation>)annotation{
    if (![annotation isKindOfClass:[CFAnnotation class]]) return nil;
    CFAnotationView *annoView = [CFAnotationView annotationViewWithMapView:mapView];
    annoView.annotation = annotation;
    return annoView;
}



//- (void)mapView:(BMKMapView *)mapView annotationViewForBubble:(CFAnotationView *)view{
//    CFAnnotation *annotation = (CFAnnotation *)view.annotation;
////    ShopDetailCtrl *ctrl = [[ShopDetailCtrl alloc] initWithShopResult:annotation.shopResult];
////    [self.navigationController pushViewController:ctrl animated:YES];
//    
//}


- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation{
    self.userLocation = userLocation;
    [_mapView updateLocationData:userLocation];
}



-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    if([keyPath isEqualToString:@"userTrackingMode"]){
        NSNumber *new = [change objectForKey:@"new"];
        if ([new integerValue] == BMKUserTrackingModeFollow) {
            self.userLocationBtn.selected = YES;
        }else{
            self.userLocationBtn.selected = NO;
        }
    }
}

-(void)dealloc{
    [self.mapView removeObserver:self forKeyPath:@"userTrackingMode"];
}


@end
